<template>
  <div style="background: #EEEEEE7F; min-height: 100vh">

    <van-nav-bar title="仪器申请" left-text="返回" left-arrow @click-left="onClickLeft" />
    <van-space direction="vertical" fill>

      <van-cell-group inset style="margin-top: 8px">

        <van-field v-model="instrumentName" label="仪器名称" placeholder="请输入仪器名称" />
        <van-cell title="仪器照片" />
        <van-uploader
            v-model="instrumentImgs"
            :after-read="afterRead"
            :before-delete="onDeleteImage"
            multiple
            max-count="5"
            preview-image
            style="margin: 0 16px"
        />

      </van-cell-group>

      <van-cell-group inset>
        <van-cell title="仪器借用位置" is-link :value="borrowRoomText || '选择房间'" @click="onSelectBorrowLocation" />
        <van-cell title="仪器归还位置" is-link :value="returnRoomText || '选择房间'" @click="onSelectReturnLocation" />
      </van-cell-group>

      <van-cell-group inset>
        <van-cell style="--van-cell-horizontal-padding: 8px">
          <van-field
              v-model="selectReviewerTextRef"
              is-link
              label="审核人"
              placeholder="选择审核人"
              readonly
              @click="showPicker = true"
          />
        </van-cell>
        <van-popup v-model:show="showPicker" destroy-on-close position="bottom" round>
          <van-picker :columns="reviewerRef" @cancel="showPicker = false" @confirm="onConfirm" />
        </van-popup>
      </van-cell-group>

      <van-cell-group inset>
        <van-field
            v-model="message"
            rows="2"
            autosize
            label="备注"
            type="textarea"
            maxlength="50"
            placeholder="请输入备注"
            show-word-limit
        />
      </van-cell-group>

      <div style="width: auto; margin: 0 16px 8px 16px">
        <van-button round type="primary" style="width: 100%;" @click="reservation">
          立即申请
        </van-button>
      </div>
    </van-space>

    <van-dialog v-model:show="showRoomSelector" show-cancel-button width="100%">
      <RoomSelector @selectRoom="onRoomSelected" select-room-type="LAB" />
    </van-dialog>
  </div>
</template>


<script setup>
import router from "@/apps/client/router.js";
import { ref } from "vue";
import {borrowInstrumentFromUp, getLoanReviewers, uploadInstrumentImage} from "@/apps/client/utils/instrumentApi.js";
import { getUserInfo } from "@/apps/client/utils/userApi.js";
import {
  showNotify,
  closeToast,
  showLoadingToast
} from "vant";
import RoomSelector from "@/apps/client/components/RoomSelector.vue";


// 页面导航
const onClickLeft = () => router.back();

// 房间选择
const showRoomSelector = ref(false);
const currentRoomType = ref('');
const borrowRoomRef = ref(null);
const returnRoomRef = ref(null);
const borrowRoomText = ref('');
const returnRoomText = ref('');

// 仪器信息
const instrumentName = ref('');
const instrumentImgs = ref([]);
const imageIds = ref([]);

// 审核人
const reviewerRef = ref([]);
const showPicker = ref(false);
const selectReviewerTextRef = ref('');
let selectReviewer = null;

// 备注 & 用户积分
const message = ref('');
const userPoints = ref('');

getUserInfo().then(({ data }) => {
  userPoints.value = data.points + "积分";
  sessionStorage.setItem("points", data.points);
});

getLoanReviewers().then(body => {
  reviewerRef.value = body.data.map(item => ({
    text: item.name,
    value: item.id
  }));
})
// 审核人选择确认
const onConfirm = ({ selectedOptions }) => {

  showPicker.value = false;
  selectReviewer = selectedOptions[0];
  selectReviewerTextRef.value = selectReviewer.text;
};

// 图片上传处理
const afterRead = async (file) => {
  showLoadingToast({ message: '上传中...', forbidClick: true, duration: 0 });

  try {
    const res = await uploadInstrumentImage(file);
    if (res.code === 200 && res.data.url) {

      const baseUrl = window.location.origin;
      const fullUrl = res.data.url.startsWith('http') ? res.data.url : `${baseUrl}/api/src/img/${res.data.url}`;

      const imgObj = {
        url: fullUrl,
        isImage: true,
        imageId: res.data.url
      }
      //instrumentImgs.value.push(imgObj);
      imageIds.value.push(res.data.url);
    } else {
      showNotify({ type: 'danger', message: '图片上传失败' });
    }
  } catch (err) {
    showNotify({ type: 'danger', message: '上传错误：' + err.message });
  } finally {
    closeToast();
  }
};


// 删除图片同步删除 imageId
const onDeleteImage = (file, { index }) => {
  const img = instrumentImgs.value[index];
  if (img?.imageId) {
    const i = imageIds.value.indexOf(img.imageId);
    if (i !== -1) imageIds.value.splice(i, 1);
  }
  return true;
};

// 房间选择逻辑
function onSelectBorrowLocation() {
  currentRoomType.value = 'borrow';
  showRoomSelector.value = true;
}
function onSelectReturnLocation() {
  currentRoomType.value = 'return';
  showRoomSelector.value = true;
}

function onRoomSelected(room) {
  if (currentRoomType.value === 'borrow') {
    borrowRoomRef.value = room;
    borrowRoomText.value = `${room.subType} ${room.number}`;
    sessionStorage.setItem("borrowRoomId", room.id);
  } else {
    returnRoomRef.value = room;
    returnRoomText.value = `${room.subType} ${room.number}`;
    sessionStorage.setItem("returnRoomId", room.id);
  }
  showRoomSelector.value = false;
}

// 提交逻辑
async function reservation() {
  if (!instrumentName.value) {
    return showNotify({ message: '请输入仪器名称' });
  }
  if (!borrowRoomRef.value || !returnRoomRef.value) {
    return showNotify({ message: '请选择借用和归还位置' });
  }
  if (imageIds.value.length === 0) {
    return showNotify({ message: '请上传至少一张图片' });
  }
  if (!selectReviewer.value) {
    return showNotify({ message: '请选择审核人' });
  }
  showLoadingToast({ message: '提交中...', forbidClick: true, duration: 0 });

  const payload = {
    reviewerId: selectReviewer.value,
    instrumentName: instrumentName.value,
    instrumentImgs: imageIds.value,
    remark: message.value,
    borrowRoomId: sessionStorage.getItem("borrowRoomId"),
    returnRoomId: sessionStorage.getItem("returnRoomId")
  };

  try {
    const res = await borrowInstrumentFromUp(payload);
    if (res.code === 200) {

      showNotify({ type: 'success', message: '申请成功' });
      const { data } = await getUserInfo();
      userPoints.value = data.points + "积分";
      sessionStorage.setItem("points", data.points);

      instrumentName.value = '';
      instrumentImgs.value = [];
      imageIds.value = [];
      borrowRoomRef.value = null;
      returnRoomRef.value = null;
      borrowRoomText.value = '';
      returnRoomText.value = '';
      selectReviewerTextRef.value = '';
      selectReviewer = null;
      message.value = '';
      sessionStorage.removeItem("borrowRoomId");
      sessionStorage.removeItem("returnRoomId");
    } else {
      showNotify({ message: res.msg || '申请失败' });
    }
  } catch (err) {
    showNotify({ message: err.response.data.msg });
  } finally {
    closeToast();
  }
}
</script>


<style scoped>
</style>
